package com.xrit.sunnyday.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Member;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.utils.RedisMessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginMobileController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @PostMapping("/check")
    public Result check(@RequestBody Map<String,String> loginInfo, HttpServletResponse response){
        //        验证码的校验
        Jedis jedis = jedisPool.getResource();
//        获取手机号码
        String telephone = loginInfo.get("telephone");
//        获取验证码的key并和手机号码拼接起来
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
//        拿到redis中的验证码
        String codeInRedis = jedis.get(key);
//        判断redis中是否有值，如果为空就从新获取验证码
        if (StringUtils.isEmpty(codeInRedis)) {
//            没有值，就从新获取验证码
            return new Result(false, "请从新获取验证码!!!");
        }
//        从前端传入的验证码
        String validateCode = loginInfo.get("validateCode");
//        判断验证码是否正确
        if (!codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
//        移除redis中的验证码，防止重复提交
        jedis.del(key);
        jedis.close();
//        通过手机号判断是否为会员
        Member member = memberService.findByTelephone(telephone);
        if(null == member){
            //7.1非会员：填充会员信息
            member = new Member();
            member.setRegTime(new Date());      //注册时间
            member.setPhoneNumber(telephone);   //注册手机号码
            member.setRemark("手机快速注册");     //标记
            //7.2添加为新会员
            memberService.add(member);
        }
//        是会员：跟踪记录的手机号码，代表着会员
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setMaxAge(30*24*60*60); // 存1个月
        cookie.setPath("/"); // 访问的路径 根路径下时 网站的所有路径 都会发送这个cookie
        response.addCookie(cookie);
//        添加成功给出提示
        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }
}
